<!-- src/components/SearchInput.vue -->
<template>
	<div :class="wrapperClass">
		<div
			class="flex items-center rounded-full px-4 py-2 transition-all duration-300 border-2 w-full"
			:class="variantClasses"
		>
			<SearchIcon
				@click="handleSearch"
				class="h-5 w-5 mr-2 flex-shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
			/>
			<input
				type="text"
				v-model="internalValue"
				:placeholder="placeholder"
				class="w-full bg-transparent text-sm focus:outline-none"
				@keyup.enter="handleSearch"
				@focus="isFocused = true"
				@blur="isFocused = false"
			/>
			<button
				v-if="internalValue"
				@click="clearInput"
				class="p-1 -mr-2"
				aria-label="Clear search"
			>
				<XIcon
					class="h-4 w-4 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
				/>
			</button>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
// 假设你的 Icon 组件在这个路径下
import SearchIcon from "@/components/icon/SearchIcon.vue";
import XIcon from "@/components/icon/XIcon.vue";

// 1. 定义 Props
const props = defineProps({
	// 使用 v-model 绑定的值
	modelValue: {
		type: String,
		required: true,
	},
	// 输入框的占位符
	placeholder: {
		type: String,
		default: "请输入搜索内容",
	},
	// 外部容器的 class
	wrapperClass: {
		type: String,
		default: "relative w-full max-w-2xl mx-auto",
	},
});

// 2. 定义 Emits
const emit = defineEmits(["update:modelValue", "search"]);

// 3. 内部状态
const isFocused = ref(false);
// 创建一个内部 ref 来同步 modelValue，这样可以直接在模板中使用 v-model
const internalValue = ref(props.modelValue);

// 监听外部 modelValue 的变化，同步到内部
watch(
	() => props.modelValue,
	newValue => {
		internalValue.value = newValue;
	}
);

// 监听内部值的变化，通过 emit 更新外部的 v-model
watch(internalValue, newValue => {
	emit("update:modelValue", newValue);
});

// 4. 计算属性，用于处理变体A的动态样式
const variantClasses = computed(() => {
	const baseClasses =
		"bg-gray-50 text-gray-600 placeholder-gray-400 dark:bg-gray-800 dark:text-gray-300 dark:placeholder-gray-500";
	const focusClasses = "border-sky-400 dark:border-sky-600";
	const blurClasses = "border-sky-100 dark:border-sky-900";

	return `${baseClasses} ${isFocused.value ? focusClasses : blurClasses}`;
});

// 5. 方法
const handleSearch = () => {
	emit("search", internalValue.value);
};

const clearInput = () => {
	internalValue.value = "";
	emit("search", "");
};
</script>
